package com.leetcode.链表;

import java.util.List;
import java.util.Stack;

//回文链表
public class lc_234 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(0);
        head.next.next = new ListNode(1);
        System.out.println(isPalindrome(head));
    }

    //给你一个单链表的头节点 head ，请你判断该链表是否为回文链表。如果是，返回 true ；否则，返回 false 。
    public static boolean isPalindrome(ListNode head) {
        //先求得链表长度count
        ListNode curNode = head;
        int count = 0;
        while (curNode != null) {
            count++;
            curNode = curNode.next;
        }
        if (count == 1) {
            return true;
        }
        //使用栈存储
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < count / 2; i++) {
            stack.push(head.val);
            head = head.next;
        }
        if (count % 2 == 1) {
            head = head.next;
        }
        while(head != null){
            if (stack.isEmpty() || stack.peek() != head.val) {
                return false;
            }
            stack.pop();
            head = head.next;
        }
        return true;
    }
}
